package me.android.library.common.ipc;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.*;
import android.util.Log;

public class IpcClient {
    private static final String TAG = "IpcClient";
    private Messenger serviceMessenger;
    private final Messenger clientMessenger = new Messenger(new IpcClientHandler());
    private boolean isBound;
    private Context context;

    // 绑定服务
    public void bind(Context context, String serviceAction) {
        this.context = context;
        Intent intent = new Intent(serviceAction);
        intent.setPackage(context.getPackageName());
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    // 解绑服务
    public void unbind() {
        if (isBound && context != null) {
            context.unbindService(connection);
            isBound = false;
        }
    }

    // 发送命令
    public void sendCommand(String command, Bundle params) {
        if (!isBound || serviceMessenger == null) return;

        Message msg = Message.obtain(null, IpcService.MSG_COMMAND);
        Bundle data = new Bundle();
        data.putString(IpcService.KEY_COMMAND, command);
        data.putBundle(IpcService.KEY_PARAMS, params);
        data.putParcelable(IpcService.KEY_CALLBACK, clientMessenger);
        msg.setData(data);

        try {
            serviceMessenger.send(msg);
        } catch (RemoteException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serviceMessenger = new Messenger(service);
            isBound = true;
            Log.d(TAG, "已连接到服务");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceMessenger = null;
            isBound = false;
            Log.d(TAG, "已断开服务连接");
        }
    };
}